import { NacosNamingClient } from 'nacos';
import logger from './logger';
import { config } from '../config';

class NacosProxy {
  _instance: NacosProxy = null;
  client: NacosNamingClient;
  static _instance: NacosProxy;
  constructor() {
    const nacosClient = new NacosNamingClient({
      logger: console,
      serverList: `${config.nacos.server.host}:${config.nacos.server.port}`,
      namespace: `${config.nacos.namespace}`
    })
    this.client = nacosClient;
    
    nacosClient.ready().then(()=>{
        const serviceName = `${config.app.name}`;//服务名
        //开始注册
        nacosClient.registerInstance(serviceName, {
            ip: `${config.app.host}`,
            port: config.app.port,
        });
    });
  }

  static instance() {
    if(!this._instance) {
      this._instance = new NacosProxy();
    }
    return this._instance;
  }
}

export async function init() {
  return NacosProxy.instance();
}

export const instance = NacosProxy.instance();

export default {
  init,
  instance: NacosProxy.instance(),
};
